/**
 * Created by kongwentao on 2016/11/1.
 */

'use strict';

function MeasureDistanceTool(map){
  this.distanceSum = 0
  this.point_line_geojson = {"type": "FeatureCollection", "features": []}
  this.linestring = {"type": "Feature", "geometry": {"type": "LineString", "coordinates": []}}
  this.map = map
}

MeasureDistanceTool.prototype.getDistance = function(){
  return this.distanceSum
}

MeasureDistanceTool.prototype.getAllPoints = function() {
  var pointsLnglat = []
  this.point_line_geojson.features.map( function(point){
    pointsLnglat.push( "["+ point.geometry.coordinates +"]" )
  })

  pointsLnglat.pop()
  return pointsLnglat
}

MeasureDistanceTool.prototype.mesureLineLenth  = function(lineStart, lineEnd) {

  var lat1 = eval(lineStart)[1]
  var lng1 = eval(lineStart)[0]
  var lat2 = eval(lineEnd)[1]
  var lng2 = eval(lineEnd)[0]

  var b = Math.PI / 180;
  var c = Math.sin((lat2 - lat1) * b / 2);
  var d = Math.sin((lng2 - lng1) * b / 2);
  var a = c * c + d * d * Math.cos(lat1 * b) * Math.cos(lat2 * b);
  return 12756274 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}

MeasureDistanceTool.prototype.mesureDistance = function(coordinates) {
  var len = coordinates.length
  this.distanceSum = 0
  for(var i=0;i<len-1;i++){
    this.distanceSum += this.mesureLineLenth(coordinates[i], coordinates[i+1])
  }
  return this.distanceSum
}

MeasureDistanceTool.prototype.pushPointFeatures  = function(e,features) {
  //因为最后一项是linestring，在每次push进来的时候要pop掉线的集合，只剩下point
  if (this.point_line_geojson.features.length > 1) {
    this.point_line_geojson.features.pop();
  }
  //过滤掉id和输入的feature相同的数据
  if (features.length) {
    var id = features[0].properties.id;
    this.point_line_geojson.features =  this.point_line_geojson.features.filter(function (point) {
      return point.properties.id !== id;
    });
  } else {
    var point = {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [
          e.lngLat.lng,
          e.lngLat.lat
        ]
      },
      "properties": {
        "id": String(new Date().getTime())
      }
    };
    //给点坐标集合增加元素
    this.point_line_geojson.features.push(point);
  }

  //给线的点坐标集合增加元素
  if ( this.point_line_geojson.features.length > 1) {
    this.linestring.geometry.coordinates =  this.point_line_geojson.features.map(function (point) {
      return point.geometry.coordinates;
    });
    this.point_line_geojson.features.push(this.linestring);
    this.mesureDistance(this.linestring.geometry.coordinates)
  }
  this.map.getSource('measure_geojson_source').setData(this.point_line_geojson);
}

MeasureDistanceTool.prototype.startMeasure  = function (map){
  map.addSource('measure_geojson_source', {
    "type": "geojson",
    "data": this.point_line_geojson
  });

  // Add styles to the map
  map.addLayer({
    id: 'measure-points',
    type: 'circle',
    source: 'measure_geojson_source',
    paint: {
      'circle-radius': 5,
      'circle-color': '#000'
    },
    filter: ['in', '$type', 'Point']
  });
  map.addLayer({
    id: 'measure-lines',
    type: 'line',
    source: 'measure_geojson_source',
    layout: {
      'line-cap': 'round',
      'line-join': 'round'
    },
    paint: {
      'line-color': '#000',
      'line-width': 2.5
    },
    filter: ['in', '$type', 'LineString']
  });
}

MeasureDistanceTool.prototype.clear  = function (){
  this.distanceSum = 0
  this.point_line_geojson = {"type": "FeatureCollection", "features": []}
  this.linestring = {"type": "Feature", "geometry": {"type": "LineString", "coordinates": []}}
  if(this.map.getSource('measure_geojson_source')){
    this.map.removeSource('measure_geojson_source')
    this.map.addSource('measure_geojson_source', {
      "type": "geojson",
      "data": this.point_line_geojson
    });
  }
}

MeasureDistanceTool.prototype.destroy  = function (){
  this.distanceSum = 0
  this.point_line_geojson = {"type": "FeatureCollection", "features": []}
  this.linestring = {"type": "Feature", "geometry": {"type": "LineString", "coordinates": []}}
  if(this.map.getLayer('measure-points')){
    this.map.removeLayer('measure-points')
  }
  if(this.map.getLayer('measure-lines')) {
    this.map.removeLayer('measure-lines')
  }
  if(this.map.getSource('measure_geojson_source')){
    map.removeSource('measure_geojson_source')
  }
}
